package com.wxm.jwt.util;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * <p>
 *      Rsa key 帮助类
 * </p>
 *
 * @author: wxm
 * @Date: 2021/10/6
 */
public class RsaKeyHelper {

    /**
     * 生成公钥，用于解析Token
     * @param pubKey 公钥字节数组
     * @return PublicKey
     * @throws Exception Exception
     */
    public static PublicKey getPublicKey(byte[] pubKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }

    /**
     * 生成私钥，用于生成Token
     * @param pubKey 公钥字节数组
     * @return PublicKey
     * @throws Exception Exception
     */
    public static PrivateKey getPrivateKey(byte[] pubKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pubKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
}
